<!DOCTYPE html>



  


<html class="theme-next gemini use-motion" lang="zh-Hans">
<head><meta name="generator" content="Hexo 3.8.0">
  <meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform">
<meta http-equiv="Cache-Control" content="no-siteapp">
















  
  
  <link href="/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css">







<link href="/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css">

<link href="/css/main.css?v=5.1.4" rel="stylesheet" type="text/css">


  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Qtcreator,MySql,">










<meta name="description" content="Qt 操作MySql数据库">
<meta name="keywords" content="Qtcreator,MySql">
<meta property="og:type" content="article">
<meta property="og:title" content="Qt实战（3）">
<meta property="og:url" content="http://Anzusen.com/2019/05/26/Qt实战（3）/index.html">
<meta property="og:site_name" content="Anzhusen">
<meta property="og:description" content="Qt 操作MySql数据库">
<meta property="og:locale" content="zh-Hans">
<meta property="og:image" content="http://anzusen.com/image/delete_dadabase.png">
<meta property="og:image" content="http://anzusen.com/image/qtablemodel.png">
<meta property="og:updated_time" content="2020-04-06T13:07:38.160Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="Qt实战（3）">
<meta name="twitter:description" content="Qt 操作MySql数据库">
<meta name="twitter:image" content="http://anzusen.com/image/delete_dadabase.png">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/',
    scheme: 'Gemini',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: '博主'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://Anzusen.com/2019/05/26/Qt实战（3）/">





  <title>Qt实战（3） | Anzhusen</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="zh-Hans">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>
    <a href="https://github.com/ananzhusen/ananzhusen.github.io" class="github-corner" aria-label="View source on GitHub"><svg width="80" height="80" viewbox="0 0 250 250" style="fill:#64CEAA; color:#fff; position: absolute; top: 0; border: 0; right: 0;" aria-hidden="true"><path d="M0,0 L115,115 L130,115 L142,142 L250,250 L250,0 Z"/><path d="M128.3,109.0 C113.8,99.7 119.0,89.6 119.0,89.6 C122.0,82.7 120.5,78.6 120.5,78.6 C119.2,72.0 123.4,76.3 123.4,76.3 C127.3,80.9 125.5,87.3 125.5,87.3 C122.9,97.6 130.6,101.9 134.4,103.2" fill="currentColor" style="transform-origin: 130px 106px;" class="octo-arm"/><path d="M115.0,115.0 C114.9,115.1 118.7,116.5 119.8,115.4 L133.7,101.6 C136.9,99.2 139.9,98.4 142.2,98.6 C133.8,88.0 127.5,74.4 143.8,58.0 C148.5,53.4 154.0,51.2 159.7,51.0 C160.3,49.4 163.2,43.6 171.4,40.1 C171.4,40.1 176.1,42.5 178.8,56.2 C183.1,58.6 187.2,61.8 190.9,65.4 C194.5,69.0 197.7,73.2 200.1,77.6 C213.8,80.2 216.3,84.9 216.3,84.9 C212.7,93.1 206.9,96.0 205.4,96.6 C205.1,102.4 203.0,107.8 198.3,112.5 C181.9,128.9 168.3,122.5 157.7,114.1 C157.9,116.9 156.7,120.9 152.7,124.9 L141.0,136.5 C139.8,137.7 141.6,141.9 141.8,141.8 Z" fill="currentColor" class="octo-body"/></svg></a><style>.github-corner:hover .octo-arm{animation:octocat-wave 560ms ease-in-out}@keyframes octocat-wave{0%,100%{transform:rotate(0)}20%,60%{transform:rotate(-25deg)}40%,80%{transform:rotate(10deg)}}@media (max-width:500px){.github-corner:hover .octo-arm{animation:none}.github-corner .octo-arm{animation:octocat-wave 560ms ease-in-out}}</style>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/" class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">Anzhusen</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br>
            
            首页
          </a>
        </li>
      
        
        <li class="menu-item menu-item-tags">
          <a href="/tags/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-tags"></i> <br>
            
            标签
          </a>
        </li>
      
        
        <li class="menu-item menu-item-categories">
          <a href="/categories/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-th"></i> <br>
            
            分类
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br>
            
            归档
          </a>
        </li>
      

      
        <li class="menu-item menu-item-search">
          
            <a href="javascript:;" class="popup-trigger">
          
            
              <i class="menu-item-icon fa fa-search fa-fw"></i> <br>
            
            搜索
          </a>
        </li>
      
    </ul>
  

  
    <div class="site-search">
      
  <div class="popup search-popup local-search-popup">
  <div class="local-search-header clearfix">
    <span class="search-icon">
      <i class="fa fa-search"></i>
    </span>
    <span class="popup-btn-close">
      <i class="fa fa-times-circle"></i>
    </span>
    <div class="local-search-input-wrapper">
      <input autocomplete="off" placeholder="搜索..." spellcheck="false" type="text" id="local-search-input">
    </div>
  </div>
  <div id="local-search-result"></div>
</div>



    </div>
  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://Anzusen.com/2019/05/26/Qt实战（3）/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="ananzhusen">
      <meta itemprop="description" content>
      <meta itemprop="image" content="/images/touxiang.JPG">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="Anzhusen">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">Qt实战（3）</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">发表于</span>
              
              <time title="创建于" itemprop="dateCreated datePublished" datetime="2019-05-26T14:04:05+08:00">
                2019-05-26
              </time>
            

            

            
          </span>

          
            <span class="post-category">
            
              <span class="post-meta-divider">|</span>
            
              <span class="post-meta-item-icon">
                <i class="fa fa-folder-o"></i>
              </span>
              
                <span class="post-meta-item-text">分类于</span>
              
              
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/QT界面/" itemprop="url" rel="index">
                    <span itemprop="name">QT界面</span>
                  </a>
                </span>

                
                
              
            </span>
          

          
            
              <span class="post-comments-count">
                <span class="post-meta-divider">|</span>
                <span class="post-meta-item-icon">
                  <i class="fa fa-comment-o"></i>
                </span>
                <a href="/2019/05/26/Qt实战（3）/#comments" itemprop="discussionUrl">
                  <span class="post-comments-count valine-comment-count" data-xid="/2019/05/26/Qt实战（3）/" itemprop="commentCount"></span>
                </a>
              </span>
            
          

          
          

          
            <span class="post-meta-divider">|</span>
            <span class="page-pv">本文总阅读量 <i class="fa fa-file-o"></i>
            <span class="busuanzi-value" id="busuanzi_value_page_pv"></span>次
            </span>
          

          
            <div class="post-wordcount">
              
                
                <span class="post-meta-item-icon">
                  <i class="fa fa-file-word-o"></i>
                </span>
                
                  <span class="post-meta-item-text">字数统计&#58;</span>
                
                <span title="字数统计">
                  2k
                </span>
              

              
                <span class="post-meta-divider">|</span>
              

              
                <span class="post-meta-item-icon">
                  <i class="fa fa-clock-o"></i>
                </span>
                
                  <span class="post-meta-item-text">阅读时长 &asymp;</span>
                
                <span title="阅读时长">
                  9
                </span>
              
            </div>
          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <h2 id="Qt-操作MySql数据库"><a href="#Qt-操作MySql数据库" class="headerlink" title="Qt 操作MySql数据库"></a>Qt 操作MySql数据库</h2><a id="more"></a>
<h3 id="配置"><a href="#配置" class="headerlink" title="配置"></a>配置</h3><p>问题：Qt连接MySQL的时候提示“QSqlDatabase: QMYSQL driver not loaded”，</p>
<p>解决办法：</p>
<ul>
<li>你的Qt Creator与MySQL位数统一的情况下，从 你的MySQL\lib目录下中将 libmysql.dll 文件复制到C:\Qt\Qt5.6.1\5.6\mingw49_32\bin中。运行程序。</li>
<li>如果你的Qt Creator与MySQL位数不统一，下载一个位数与你的Qt相同的Mysql,找到里面的 libmysql.dll文件复制到目录下。</li>
<li>总之，必须保证你拿到libmysql.dll这个文件对应的mysql的位数必须与QT的位数相同。</li>
</ul>
<h3 id="数据库基本操作"><a href="#数据库基本操作" class="headerlink" title="数据库基本操作"></a>数据库基本操作</h3><p>对数据库基本操作就是增、删、改、查。</p>
<ol>
<li>新建 Qt Widgets 应用， 项目名称为 database， 类名为Mywidget， 基类选择QWidget。</li>
<li>完成后在 database.pro文件中添加如下代码：</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">QT += sql</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>连接数据库，在构造函数中添加以下代码</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlDatabase&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QDebug&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QMessageBox&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlError&gt;</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">Widget::Widget(QWidget *parent) :</span><br><span class="line">    QWidget(parent),</span><br><span class="line">    ui(<span class="keyword">new</span> Ui::Widget)</span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;setupUi(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">    打印QT支持的数据库驱动</span><br><span class="line">    qDebug()&lt;&lt;QSqlDatabase::drivers();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//添加mysql数据库</span></span><br><span class="line">    QSqlDatabase db = QSqlDatabase::addDatabase(<span class="string">"QMYSQL"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//连接数据库</span></span><br><span class="line">    db.setHostName(<span class="string">"127.0.0.1"</span>);</span><br><span class="line">    db.setUserName(<span class="string">"root"</span>);</span><br><span class="line">    db.setPassword(<span class="string">"an1234"</span>);</span><br><span class="line">    db.setDatabaseName(<span class="string">"test_db"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//打开数据库是否成功</span></span><br><span class="line">    <span class="keyword">if</span>(!db.open())</span><br><span class="line">    &#123;</span><br><span class="line">        QMessageBox::warning(<span class="keyword">this</span>,<span class="string">"错误"</span>,db.lastError().text());</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line">  &#125;</span><br></pre></td></tr></table></figure>
<p>QT支持的数据库驱动有：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">(&quot;QSQLITE&quot;, &quot;QMYSQL&quot;, &quot;QMYSQL3&quot;, &quot;QPSQL&quot;, &quot;QPSQL7&quot;)</span><br></pre></td></tr></table></figure></p>
<ol start="4">
<li>创建数据表格，继续向后添加代码</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlQuery&gt;//一组数据</span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//创建数据表格</span></span><br><span class="line">    QSqlQuery query;</span><br><span class="line">    query.exec(<span class="string">"create table student(id int primary key auto_increment ,name varchar(255),age int,score int);"</span>);</span><br></pre></td></tr></table></figure>
<p>此条语句运行一次后要注释，不能多次创建同名的数据表格</p>
<ol start="4">
<li>数据库的另一种操作</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">  </span><br><span class="line"><span class="comment">//添加mysql数据库  a是连接名，用于区分</span></span><br><span class="line">QSqlDatabase db1 = QSqlDatabase::addDatabase(<span class="string">"QMYSQL"</span>,<span class="string">"a"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//连接数据库</span></span><br><span class="line">db1.setHostName(<span class="string">"127.0.0.1"</span>);</span><br><span class="line">db1.setUserName(<span class="string">"root"</span>);</span><br><span class="line">db1.setPassword(<span class="string">"an1234"</span>);</span><br><span class="line">db1.setDatabaseName(<span class="string">"testdb"</span>);</span><br><span class="line"></span><br><span class="line"><span class="comment">//打开数据库是否成功</span></span><br><span class="line"><span class="keyword">if</span>(!db1.open())</span><br><span class="line">&#123;</span><br><span class="line">    QMessageBox::warning(<span class="keyword">this</span>,<span class="string">"错误"</span>,db.lastError().text());</span><br><span class="line">    <span class="keyword">return</span>;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="function">QSqlQuery <span class="title">query1</span><span class="params">(db1)</span></span>;<span class="comment">//有区分时，一定要加上数据库名</span></span><br><span class="line">query1.exec(<span class="string">"create table student(id int primary key auto_increment ,name varchar(255),age int,score int);"</span>);</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>插入(增)</li>
</ol>
<p>① 插入一条数据</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="comment">//插入数据</span></span><br><span class="line">   QSqlQuery query;</span><br><span class="line">   query.exec(<span class="string">"insert into student (id, name, age, score)values(2,'lucy',22,59);"</span>);</span><br></pre></td></tr></table></figure>
<p>② 批量插入<br>两种方法：<br>obdc风格</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QVariantList&gt;//放任何类型，列表 </span></span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//obdc风格插入</span></span><br><span class="line">    <span class="comment">//预处理语句</span></span><br><span class="line">    <span class="comment">//？相当于占位符</span></span><br><span class="line">    query.prepare(<span class="string">"insert into student (name, age, score)values(?,?,?);"</span>);</span><br><span class="line">    <span class="comment">//给字段设置内容</span></span><br><span class="line">    QVariantList namelist;</span><br><span class="line">    namelist &lt;&lt; <span class="string">"xiaoming"</span> &lt;&lt; <span class="string">"xiaohua"</span> &lt;&lt; <span class="string">"xiaoliao"</span>;</span><br><span class="line">    QVariantList agelist;</span><br><span class="line">    agelist &lt;&lt; <span class="number">19</span> &lt;&lt; <span class="number">20</span> &lt;&lt; <span class="number">21</span>;</span><br><span class="line">    QVariantList scorelist;</span><br><span class="line">    scorelist &lt;&lt; <span class="number">98</span> &lt;&lt; <span class="number">88</span> &lt;&lt; <span class="number">99</span>;</span><br><span class="line">    <span class="comment">//给字段绑定相应的值，按顺序绑定</span></span><br><span class="line">    query.addBindValue(namelist);</span><br><span class="line">    query.addBindValue(agelist);</span><br><span class="line">    query.addBindValue(scorelist);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//执行预处理命令</span></span><br><span class="line">    query.execBatch();</span><br></pre></td></tr></table></figure>
<p>oracle风格<br><figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//oracle风格</span></span><br><span class="line"><span class="comment">//占位符 ： + 自定义名字</span></span><br><span class="line"></span><br><span class="line">query.prepare(<span class="string">"insert into student (name, age, score)values(:name, :age, :score);"</span>);</span><br><span class="line"><span class="comment">//给字段设置内容</span></span><br><span class="line">QVariantList namelist;</span><br><span class="line">namelist &lt;&lt; <span class="string">"xiaoa"</span> &lt;&lt; <span class="string">"xiaob"</span> &lt;&lt; <span class="string">"xiaoc"</span>;</span><br><span class="line">QVariantList agelist;</span><br><span class="line">agelist &lt;&lt; <span class="number">19</span> &lt;&lt; <span class="number">20</span> &lt;&lt; <span class="number">21</span>;</span><br><span class="line">QVariantList scorelist;</span><br><span class="line">scorelist &lt;&lt; <span class="number">98</span> &lt;&lt; <span class="number">88</span> &lt;&lt; <span class="number">99</span>;</span><br><span class="line"><span class="comment">//给字段绑定  可以不按照顺序</span></span><br><span class="line">query.bindValue(<span class="string">":name"</span>,namelist);</span><br><span class="line">query.bindValue(<span class="string">":score"</span>,scorelist);</span><br><span class="line">query.bindValue(<span class="string">":age"</span>,agelist);</span><br><span class="line"></span><br><span class="line"><span class="comment">//执行预处理命令</span></span><br><span class="line">query.execBatch();</span><br></pre></td></tr></table></figure></p>
<ol start="6">
<li>更新数据（改）</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><span class="line">QSqlQuery query;</span><br><span class="line">query.exec(<span class="string">"update student set score = 72 where id = 3"</span>);</span><br></pre></td></tr></table></figure>
<ol start="7">
<li>查找并打印（查）</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line">QSqlQuery query;</span><br><span class="line">query.exec(<span class="string">"select * from student where name = 'xiaob' "</span>);<span class="comment">//过滤</span></span><br><span class="line"><span class="keyword">while</span>(query.next())<span class="comment">//一行一行的查找，一直到没有返回false</span></span><br><span class="line">&#123;</span><br><span class="line">    qDebug()&lt;&lt;query.value(<span class="number">0</span>).toInt()</span><br><span class="line">         &lt;&lt;query.value(<span class="number">1</span>).toString()</span><br><span class="line">        &lt;&lt;query.value(<span class="string">"age"</span>).toInt()</span><br><span class="line">       &lt;&lt;query.value(<span class="number">3</span>).toInt();</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="8">
<li>在界面上执行删除操作（删）</li>
</ol>
<p>①设计页面如图所示<br><img src="/image/delete_dadabase.png" alt></p>
<p>②右击按钮转到槽</p>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br></pre></td><td class="code"><pre><span class="line"></span><br><span class="line"><span class="keyword">void</span> Widget::on_buttondelete_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//获取行编辑器内容</span></span><br><span class="line">    QString name = ui-&gt;lineEdit-&gt;text();</span><br><span class="line">    QString sql = QString(<span class="string">"delete from student where name ='%1'"</span>).arg(name);</span><br><span class="line">    <span class="comment">//开启一个事务  QSqlDatabase::database()获取你操作的数据库</span></span><br><span class="line">    <span class="comment">//事务是数据库的一个重要功能，所谓事务是用户定义的一个数据库操作序列，这些操作要么全做要么全不做，是一个不可分割的工作单位。</span></span><br><span class="line">    <span class="comment">//qDebug()&lt;&lt; QSqlDatabase::database().transaction();//有的版本不支持这种用法</span></span><br><span class="line">    QSqlQuery query;</span><br><span class="line">    query.exec(<span class="string">"START TRANSACTION"</span>);</span><br><span class="line">    query.exec(sql);</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> Widget::on_buttonsure_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//确认删除</span></span><br><span class="line">    QSqlDatabase::database().commit();</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> Widget::on_buttoncancel_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//回滚，撤销</span></span><br><span class="line">    qDebug()&lt;&lt;<span class="string">"hahahhahh"</span>;</span><br><span class="line">    QSqlDatabase::database().rollback();</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="本地数据库Sqlite"><a href="#本地数据库Sqlite" class="headerlink" title="本地数据库Sqlite"></a>本地数据库Sqlite</h3><ol>
<li>新建 Qt Widgets 应用， 项目名称为 Sqlite， 类名为Mywidget， 基类选择QWidget。</li>
<li>在你的Sqlite相同目录下创建文件info.db</li>
<li>在.pro文件中添加</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">QT+= sql</span><br></pre></td></tr></table></figure>
<ol start="4">
<li>操作，同mysql的操作基本一样，因为是本地数据库，所以没有连接数据库的操作</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlDatabase&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QDebug&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QMessageBox&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlError&gt;//</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlQuery&gt;//一组数据</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QVariantList&gt;//放任何类型，列表</span></span></span><br><span class="line"></span><br><span class="line">MyWidget::MyWidget(QWidget *parent) :</span><br><span class="line">    QWidget(parent),</span><br><span class="line">    ui(<span class="keyword">new</span> Ui::MyWidget)</span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;setupUi(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//打印QT支持的数据库驱动</span></span><br><span class="line">    qDebug()&lt;&lt;QSqlDatabase::drivers();</span><br><span class="line">    </span><br><span class="line">    <span class="comment">//添加qsqlite数据库 本地数据库</span></span><br><span class="line">    <span class="comment">//不是很大型的数据库</span></span><br><span class="line">    QSqlDatabase db = QSqlDatabase::addDatabase(<span class="string">"QSQLITE"</span>);</span><br><span class="line"></span><br><span class="line">    db.setDatabaseName(<span class="string">"../info.db"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//打开数据库是否成功</span></span><br><span class="line">    <span class="keyword">if</span>(!db.open())</span><br><span class="line">    &#123;</span><br><span class="line">        QMessageBox::warning(<span class="keyword">this</span>,<span class="string">"错误"</span>,db.lastError().text());</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//创建数据表格</span></span><br><span class="line">    QSqlQuery query;<span class="comment">//不支持自动添加id功能</span></span><br><span class="line">    query.exec(<span class="string">"create table student(id int primary key,name varchar(255),age int,score int);"</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    query.prepare(<span class="string">"insert into student (name, age, score)values(?,?,?);"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//给字段设置内容</span></span><br><span class="line">    QVariantList namelist;</span><br><span class="line">    namelist &lt;&lt; <span class="string">"xiaoming"</span> &lt;&lt; <span class="string">"xiaohua"</span> &lt;&lt; <span class="string">"xiaoliao"</span>;</span><br><span class="line">    QVariantList agelist;</span><br><span class="line">    agelist &lt;&lt; <span class="number">19</span> &lt;&lt; <span class="number">20</span> &lt;&lt; <span class="number">21</span>;</span><br><span class="line">    QVariantList scorelist;</span><br><span class="line">    scorelist &lt;&lt; <span class="number">98</span> &lt;&lt; <span class="number">88</span> &lt;&lt; <span class="number">99</span>;</span><br><span class="line">    <span class="comment">//给字段绑定相应的值，按顺序绑定</span></span><br><span class="line">    query.addBindValue(namelist);</span><br><span class="line">    query.addBindValue(agelist);</span><br><span class="line">    query.addBindValue(scorelist);</span><br><span class="line">    query.execBatch();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//查找并打印</span></span><br><span class="line">    query.exec(<span class="string">"select * from student"</span>);</span><br><span class="line">    <span class="keyword">while</span>(query.next())<span class="comment">//一行一行的查找，一直到没有返回false</span></span><br><span class="line">    &#123;</span><br><span class="line">        qDebug()&lt;&lt;query.value(<span class="number">0</span>).toInt()</span><br><span class="line">             &lt;&lt;query.value(<span class="number">1</span>).toString()</span><br><span class="line">            &lt;&lt;query.value(<span class="string">"age"</span>).toInt()</span><br><span class="line">           &lt;&lt;query.value(<span class="number">3</span>).toInt();</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<h3 id="QTableModel类实现对数据库的可视化操作"><a href="#QTableModel类实现对数据库的可视化操作" class="headerlink" title="QTableModel类实现对数据库的可视化操作"></a>QTableModel类实现对数据库的可视化操作</h3><p>QSqlTableModel，该类提供了一个可读写单张SQL表的可编辑数据模型。下面实际操作一下</p>
<ol>
<li>新建 Qt Widgets 应用， 项目名称为sqlModel， 类名为Mywidget， 基类选择QWidget。</li>
<li>在.pro文件中添加</li>
</ol>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">QT+= sql</span><br></pre></td></tr></table></figure>
<ol start="3">
<li>设计界面如图所示<br><img src="/image/qtablemodel.png" alt></li>
</ol>
<p>注意：和里面的显示数据库的框用的是Item Views(Model-Based)里的TableView。</p>
<ol start="4">
<li>在头文件中添加库和对象</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlTableModel&gt;</span></span></span><br><span class="line"></span><br><span class="line"><span class="keyword">private</span>:</span><br><span class="line">    Ui::MyWidget *ui;</span><br><span class="line"></span><br><span class="line">    QSqlTableModel *model;</span><br></pre></td></tr></table></figure>
<ol start="5">
<li>实现可视化操作</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlDatabase&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QDebug&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QMessageBox&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlError&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlTableModel&gt;</span></span></span><br><span class="line"><span class="meta">#<span class="meta-keyword">include</span><span class="meta-string">&lt;QSqlRecord&gt;//数据库操作记录</span></span></span><br><span class="line"></span><br><span class="line">MyWidget::MyWidget(QWidget *parent) :</span><br><span class="line">    QWidget(parent),</span><br><span class="line">    ui(<span class="keyword">new</span> Ui::MyWidget)</span><br><span class="line">&#123;</span><br><span class="line">    ui-&gt;setupUi(<span class="keyword">this</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//添加mysql数据库</span></span><br><span class="line">    QSqlDatabase db = QSqlDatabase::addDatabase(<span class="string">"QMYSQL"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//连接数据库</span></span><br><span class="line">    db.setHostName(<span class="string">"127.0.0.1"</span>);</span><br><span class="line">    db.setUserName(<span class="string">"root"</span>);</span><br><span class="line">    db.setPassword(<span class="string">"an1234"</span>);</span><br><span class="line">    db.setDatabaseName(<span class="string">"test_db"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//打开数据库是否成功</span></span><br><span class="line">    <span class="keyword">if</span>(!db.open())</span><br><span class="line">    &#123;</span><br><span class="line">        QMessageBox::warning(<span class="keyword">this</span>,<span class="string">"错误"</span>,db.lastError().text());</span><br><span class="line">        <span class="keyword">return</span>;</span><br><span class="line">    &#125;</span><br><span class="line"></span><br><span class="line">    <span class="comment">//设置模型</span></span><br><span class="line">    model = <span class="keyword">new</span> QSqlTableModel(<span class="keyword">this</span>);</span><br><span class="line">    model-&gt;setTable(<span class="string">"student"</span>);<span class="comment">//指定使用那个表</span></span><br><span class="line"></span><br><span class="line">    <span class="comment">//把model放在view</span></span><br><span class="line">    ui-&gt;tableView-&gt;setModel(model);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//显示model里的数据</span></span><br><span class="line">    model-&gt;select();</span><br><span class="line"></span><br><span class="line">    <span class="comment">//字段设置为指定中文名 第0个字段即id</span></span><br><span class="line">    model-&gt;setHeaderData(<span class="number">0</span>,Qt::Horizontal,<span class="string">"学号"</span>);</span><br><span class="line">    model-&gt;setHeaderData(<span class="number">1</span>,Qt::Horizontal,<span class="string">"姓名"</span>);</span><br><span class="line">    model-&gt;setHeaderData(<span class="number">2</span>,Qt::Horizontal,<span class="string">"年龄"</span>);</span><br><span class="line">    model-&gt;setHeaderData(<span class="number">3</span>,Qt::Horizontal,<span class="string">"分数"</span>);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//设置model的编辑模式 为手动提交</span></span><br><span class="line">    model-&gt;setEditStrategy(QSqlTableModel::OnManualSubmit);</span><br><span class="line"></span><br><span class="line">    <span class="comment">//设置view中的数据库为不能修改</span></span><br><span class="line">    <span class="comment">//ui-&gt;tableView-&gt;setEditTriggers(QAbstractItemView::NoEditTriggers);</span></span><br><span class="line"></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>
<ol start="6">
<li>按钮槽函数添加代码</li>
</ol>
<figure class="highlight c++"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//改</span></span><br><span class="line"><span class="comment">//修改操作可以直接在视图框中操作</span></span><br><span class="line"></span><br><span class="line"></span><br><span class="line"><span class="comment">//增</span></span><br><span class="line"><span class="keyword">void</span> MyWidget::on_buttonadd_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//添加空记录</span></span><br><span class="line">    QSqlRecord record = model-&gt;record();</span><br><span class="line">    <span class="comment">//获取行号</span></span><br><span class="line">    <span class="keyword">int</span> row = model-&gt;rowCount();</span><br><span class="line">    model-&gt;insertRecord(row,record);</span><br><span class="line"></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//删</span></span><br><span class="line"><span class="keyword">void</span> MyWidget::on_buttondelete_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//获取选中的模型</span></span><br><span class="line">    QItemSelectionModel *sModel=ui-&gt;tableView-&gt;selectionModel();</span><br><span class="line">    <span class="comment">//取出选中模型中的索引（哪几行）</span></span><br><span class="line">    QModelIndexList <span class="built_in">list</span> = sModel-&gt;selectedRows();</span><br><span class="line">    <span class="comment">//删除所有选中的行</span></span><br><span class="line">    <span class="keyword">for</span>(<span class="keyword">int</span> i=<span class="number">0</span> ;i&lt;<span class="built_in">list</span>.size();i++)</span><br><span class="line">    &#123;</span><br><span class="line">        model-&gt;removeRow(<span class="built_in">list</span>.at(i).row());</span><br><span class="line">        <span class="comment">//取出所有索引中的i行的索引，再根据这个索引选中并删除这一行</span></span><br><span class="line">    &#125;</span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> MyWidget::on_buttonsure_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    model-&gt;submitAll();<span class="comment">//提交动作</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="keyword">void</span> MyWidget::on_buttoncancel_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    model-&gt;revertAll();<span class="comment">//取消动作</span></span><br><span class="line">    model-&gt;submitAll();<span class="comment">//提交动作（取消也是一个动作）</span></span><br><span class="line">&#125;</span><br><span class="line"></span><br><span class="line"><span class="comment">//查</span></span><br><span class="line"><span class="keyword">void</span> MyWidget::on_buttonsure_2_clicked()</span><br><span class="line">&#123;</span><br><span class="line">    <span class="comment">//获取行编辑器内容</span></span><br><span class="line">    QString name = ui-&gt;lineEdit-&gt;text();</span><br><span class="line">    <span class="comment">//过滤条件</span></span><br><span class="line">    QString str = QString(<span class="string">"name='%1'"</span>).arg(name);</span><br><span class="line">    model-&gt;setFilter(str);</span><br><span class="line">    model-&gt;select();<span class="comment">//重新显示model里的数据</span></span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

      
    </div>
    
    
    

    

    
      <div>
        <div style="padding: 10px 0; margin: 20px auto; width: 90%; text-align: center;">
  <div>你可以对我进行打赏哦</div>
  <button id="rewardButton" disable="enable" onclick="var qr = document.getElementById('QR'); if (qr.style.display === 'none') {qr.style.display='block';} else {qr.style.display='none'}">
    <span>打赏</span>
  </button>
  <div id="QR" style="display: none;">

    
      <div id="wechat" style="display: inline-block">
        <img id="wechat_qr" src="/images/weichat.jpg" alt="ananzhusen 微信支付">
        <p>微信支付</p>
      </div>
    

    
      <div id="alipay" style="display: inline-block">
        <img id="alipay_qr" src="/images/alipay.jpg" alt="ananzhusen 支付宝">
        <p>支付宝</p>
      </div>
    

    

  </div>
</div>

      </div>
    

    

    <footer class="post-footer">
      
        <div class="post-tags">
          
            <a href="/tags/Qtcreator/" rel="tag"># Qtcreator</a>
          
            <a href="/tags/MySql/" rel="tag"># MySql</a>
          
        </div>
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/2019/05/19/Qt实战（2）/" rel="next" title="Qt实战（2）">
                <i class="fa fa-chevron-left"></i> Qt实战（2）
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/2019/06/08/Python爬虫（1）/" rel="prev" title="Python爬虫">
                Python爬虫 <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
        <!-- JiaThis Button BEGIN -->
<div class="jiathis_style">
<span class="jiathis_txt">分享到：</span>
<a class="jiathis_button_fav">收藏夹</a>
<a class="jiathis_button_copy">复制网址</a>
<a class="jiathis_button_email">邮件</a>
<a class="jiathis_button_weixin">微信</a>
<a class="jiathis_button_qzone">QQ空间</a>
<a class="jiathis_button_tqq">腾讯微博</a>
<a class="jiathis_button_douban">豆瓣</a>
<a class="jiathis_button_share">一键分享</a>

<a href="http://www.jiathis.com/share?uid=2140465" class="jiathis jiathis_txt jiathis_separator jtico jtico_jiathis" target="_blank">更多</a>
<a class="jiathis_counter_style"></a>
</div>
<script type="text/javascript">
var jiathis_config={
  data_track_clickback:true,
  summary:"",
  shortUrl:false,
  hideMore:false
}
</script>
<script type="text/javascript" src="http://v3.jiathis.com/code/jia.js?uid=" charset="utf-8"></script>
<!-- JiaThis Button END -->
      
    </div>
  </div>


          </div>
          


          

  
    <div class="comments" id="comments">
    </div>
  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      
        <ul class="sidebar-nav motion-element">
          <li class="sidebar-nav-toc sidebar-nav-active" data-target="post-toc-wrap">
            文章目录
          </li>
          <li class="sidebar-nav-overview" data-target="site-overview-wrap">
            站点概览
          </li>
        </ul>
      

      <section class="site-overview-wrap sidebar-panel">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image" src="/images/touxiang.JPG" alt="ananzhusen">
            
              <p class="site-author-name" itemprop="name">ananzhusen</p>
              <p class="site-description motion-element" itemprop="description"></p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/archives/">
              
                  <span class="site-state-item-count">23</span>
                  <span class="site-state-item-name">日志</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-categories">
                <a href="/categories/index.html">
                  <span class="site-state-item-count">13</span>
                  <span class="site-state-item-name">分类</span>
                </a>
              </div>
            

            
              
              
              <div class="site-state-item site-state-tags">
                <a href="/tags/index.html">
                  <span class="site-state-item-count">43</span>
                  <span class="site-state-item-name">标签</span>
                </a>
              </div>
            

          </nav>

          

          
            <div class="links-of-author motion-element">
                
                  <span class="links-of-author-item">
                    <a href="https://github.com/ananzhusen" target="_blank" title="GitHub">
                      
                        <i class="fa fa-fw fa-github"></i>GitHub</a>
                  </span>
                
                  <span class="links-of-author-item">
                    <a href="https://weibo.com/5817162963" target="_blank" title="weibo">
                      
                        <i class="fa fa-fw fa-weibo"></i>weibo</a>
                  </span>
                
            </div>
          

          
          

          
          
            <div class="links-of-blogroll motion-element links-of-blogroll-block">
              <div class="links-of-blogroll-title">
                <i class="fa  fa-fw fa-link"></i>
                Links
              </div>
              <ul class="links-of-blogroll-list">
                
                  <li class="links-of-blogroll-item">
                    <a href="https://gitee.com/anzhusen/" title="gitee" target="_blank">gitee</a>
                  </li>
                
              </ul>
            </div>
          

          

        </div>
      </section>

      
      <!--noindex-->
        <section class="post-toc-wrap motion-element sidebar-panel sidebar-panel-active">
          <div class="post-toc">

            
              
            

            
              <div class="post-toc-content"><ol class="nav"><li class="nav-item nav-level-2"><a class="nav-link" href="#Qt-操作MySql数据库"><span class="nav-number">1.</span> <span class="nav-text">Qt 操作MySql数据库</span></a><ol class="nav-child"><li class="nav-item nav-level-3"><a class="nav-link" href="#配置"><span class="nav-number">1.1.</span> <span class="nav-text">配置</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#数据库基本操作"><span class="nav-number">1.2.</span> <span class="nav-text">数据库基本操作</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#本地数据库Sqlite"><span class="nav-number">1.3.</span> <span class="nav-text">本地数据库Sqlite</span></a></li><li class="nav-item nav-level-3"><a class="nav-link" href="#QTableModel类实现对数据库的可视化操作"><span class="nav-number">1.4.</span> <span class="nav-text">QTableModel类实现对数据库的可视化操作</span></a></li></ol></li></ol></div>
            

          </div>
        </section>
      <!--/noindex-->
      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2021</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">ananzhusen</span>

  
</div>

<!-- 
  <div class="powered-by">由 <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a> 强力驱动</div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">主题 &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Gemini</a> v5.1.4</div>
 -->



        
<div class="busuanzi-count">
  <script async src="https://dn-lbstatics.qbox.me/busuanzi/2.3/busuanzi.pure.mini.js"></script>

  
    <span class="site-uv">
      本站访客数 <i class="fa fa-user"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_uv"></span>
      人次
    </span>
  

  
    <span class="site-pv">
      本站访问总量 <i class="fa fa-eye"></i>
      <span class="busuanzi-value" id="busuanzi_value_site_pv"></span>
      次
    </span>
  
</div>








        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  


  











  
  
    <script type="text/javascript" src="/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  

  
  
    <script type="text/javascript" src="/lib/canvas-nest/canvas-nest.min.js"></script>
  


  


  <script type="text/javascript" src="/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  










  <script src="//cdn1.lncld.net/static/js/3.0.4/av-min.js"></script>
  <script src="//unpkg.com/valine/dist/Valine.min.js"></script>
  
  <script type="text/javascript">
    var GUEST = ['nick','mail','link'];
    var guest = 'nick,mail,link';
    guest = guest.split(',').filter(item=>{
      return GUEST.indexOf(item)>-1;
    });
    new Valine({
        el: '#comments' ,
        verify: false,
        notify: false,
        appId: 'e69lyQSoCtoaLGljT3kXLBEQ-gzGzoHsz',
        appKey: 'pRDcFfyQnO4jQWxElUFupJ2D',
        placeholder: 'Just go go',
        avatar:'mm',
        guest_info:guest,
        pageSize:'10' || 10,
    });
  </script>



  

  <script type="text/javascript">
    // Popup Window;
    var isfetched = false;
    var isXml = true;
    // Search DB path;
    var search_path = "search.xml";
    if (search_path.length === 0) {
      search_path = "search.xml";
    } else if (/json$/i.test(search_path)) {
      isXml = false;
    }
    var path = "/" + search_path;
    // monitor main search box;

    var onPopupClose = function (e) {
      $('.popup').hide();
      $('#local-search-input').val('');
      $('.search-result-list').remove();
      $('#no-result').remove();
      $(".local-search-pop-overlay").remove();
      $('body').css('overflow', '');
    }

    function proceedsearch() {
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay"></div>')
        .css('overflow', 'hidden');
      $('.search-popup-overlay').click(onPopupClose);
      $('.popup').toggle();
      var $localSearchInput = $('#local-search-input');
      $localSearchInput.attr("autocapitalize", "none");
      $localSearchInput.attr("autocorrect", "off");
      $localSearchInput.focus();
    }

    // search function;
    var searchFunc = function(path, search_id, content_id) {
      'use strict';

      // start loading animation
      $("body")
        .append('<div class="search-popup-overlay local-search-pop-overlay">' +
          '<div id="search-loading-icon">' +
          '<i class="fa fa-spinner fa-pulse fa-5x fa-fw"></i>' +
          '</div>' +
          '</div>')
        .css('overflow', 'hidden');
      $("#search-loading-icon").css('margin', '20% auto 0 auto').css('text-align', 'center');

      $.ajax({
        url: path,
        dataType: isXml ? "xml" : "json",
        async: true,
        success: function(res) {
          // get the contents from search data
          isfetched = true;
          $('.popup').detach().appendTo('.header-inner');
          var datas = isXml ? $("entry", res).map(function() {
            return {
              title: $("title", this).text(),
              content: $("content",this).text(),
              url: $("url" , this).text()
            };
          }).get() : res;
          var input = document.getElementById(search_id);
          var resultContent = document.getElementById(content_id);
          var inputEventFunction = function() {
            var searchText = input.value.trim().toLowerCase();
            var keywords = searchText.split(/[\s\-]+/);
            if (keywords.length > 1) {
              keywords.push(searchText);
            }
            var resultItems = [];
            if (searchText.length > 0) {
              // perform local searching
              datas.forEach(function(data) {
                var isMatch = false;
                var hitCount = 0;
                var searchTextCount = 0;
                var title = data.title.trim();
                var titleInLowerCase = title.toLowerCase();
                var content = data.content.trim().replace(/<[^>]+>/g,"");
                var contentInLowerCase = content.toLowerCase();
                var articleUrl = decodeURIComponent(data.url);
                var indexOfTitle = [];
                var indexOfContent = [];
                // only match articles with not empty titles
                if(title != '') {
                  keywords.forEach(function(keyword) {
                    function getIndexByWord(word, text, caseSensitive) {
                      var wordLen = word.length;
                      if (wordLen === 0) {
                        return [];
                      }
                      var startPosition = 0, position = [], index = [];
                      if (!caseSensitive) {
                        text = text.toLowerCase();
                        word = word.toLowerCase();
                      }
                      while ((position = text.indexOf(word, startPosition)) > -1) {
                        index.push({position: position, word: word});
                        startPosition = position + wordLen;
                      }
                      return index;
                    }

                    indexOfTitle = indexOfTitle.concat(getIndexByWord(keyword, titleInLowerCase, false));
                    indexOfContent = indexOfContent.concat(getIndexByWord(keyword, contentInLowerCase, false));
                  });
                  if (indexOfTitle.length > 0 || indexOfContent.length > 0) {
                    isMatch = true;
                    hitCount = indexOfTitle.length + indexOfContent.length;
                  }
                }

                // show search results

                if (isMatch) {
                  // sort index by position of keyword

                  [indexOfTitle, indexOfContent].forEach(function (index) {
                    index.sort(function (itemLeft, itemRight) {
                      if (itemRight.position !== itemLeft.position) {
                        return itemRight.position - itemLeft.position;
                      } else {
                        return itemLeft.word.length - itemRight.word.length;
                      }
                    });
                  });

                  // merge hits into slices

                  function mergeIntoSlice(text, start, end, index) {
                    var item = index[index.length - 1];
                    var position = item.position;
                    var word = item.word;
                    var hits = [];
                    var searchTextCountInSlice = 0;
                    while (position + word.length <= end && index.length != 0) {
                      if (word === searchText) {
                        searchTextCountInSlice++;
                      }
                      hits.push({position: position, length: word.length});
                      var wordEnd = position + word.length;

                      // move to next position of hit

                      index.pop();
                      while (index.length != 0) {
                        item = index[index.length - 1];
                        position = item.position;
                        word = item.word;
                        if (wordEnd > position) {
                          index.pop();
                        } else {
                          break;
                        }
                      }
                    }
                    searchTextCount += searchTextCountInSlice;
                    return {
                      hits: hits,
                      start: start,
                      end: end,
                      searchTextCount: searchTextCountInSlice
                    };
                  }

                  var slicesOfTitle = [];
                  if (indexOfTitle.length != 0) {
                    slicesOfTitle.push(mergeIntoSlice(title, 0, title.length, indexOfTitle));
                  }

                  var slicesOfContent = [];
                  while (indexOfContent.length != 0) {
                    var item = indexOfContent[indexOfContent.length - 1];
                    var position = item.position;
                    var word = item.word;
                    // cut out 100 characters
                    var start = position - 20;
                    var end = position + 80;
                    if(start < 0){
                      start = 0;
                    }
                    if (end < position + word.length) {
                      end = position + word.length;
                    }
                    if(end > content.length){
                      end = content.length;
                    }
                    slicesOfContent.push(mergeIntoSlice(content, start, end, indexOfContent));
                  }

                  // sort slices in content by search text's count and hits' count

                  slicesOfContent.sort(function (sliceLeft, sliceRight) {
                    if (sliceLeft.searchTextCount !== sliceRight.searchTextCount) {
                      return sliceRight.searchTextCount - sliceLeft.searchTextCount;
                    } else if (sliceLeft.hits.length !== sliceRight.hits.length) {
                      return sliceRight.hits.length - sliceLeft.hits.length;
                    } else {
                      return sliceLeft.start - sliceRight.start;
                    }
                  });

                  // select top N slices in content

                  var upperBound = parseInt('1');
                  if (upperBound >= 0) {
                    slicesOfContent = slicesOfContent.slice(0, upperBound);
                  }

                  // highlight title and content

                  function highlightKeyword(text, slice) {
                    var result = '';
                    var prevEnd = slice.start;
                    slice.hits.forEach(function (hit) {
                      result += text.substring(prevEnd, hit.position);
                      var end = hit.position + hit.length;
                      result += '<b class="search-keyword">' + text.substring(hit.position, end) + '</b>';
                      prevEnd = end;
                    });
                    result += text.substring(prevEnd, slice.end);
                    return result;
                  }

                  var resultItem = '';

                  if (slicesOfTitle.length != 0) {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + highlightKeyword(title, slicesOfTitle[0]) + "</a>";
                  } else {
                    resultItem += "<li><a href='" + articleUrl + "' class='search-result-title'>" + title + "</a>";
                  }

                  slicesOfContent.forEach(function (slice) {
                    resultItem += "<a href='" + articleUrl + "'>" +
                      "<p class=\"search-result\">" + highlightKeyword(content, slice) +
                      "...</p>" + "</a>";
                  });

                  resultItem += "</li>";
                  resultItems.push({
                    item: resultItem,
                    searchTextCount: searchTextCount,
                    hitCount: hitCount,
                    id: resultItems.length
                  });
                }
              })
            };
            if (keywords.length === 1 && keywords[0] === "") {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-search fa-5x" /></div>'
            } else if (resultItems.length === 0) {
              resultContent.innerHTML = '<div id="no-result"><i class="fa fa-frown-o fa-5x" /></div>'
            } else {
              resultItems.sort(function (resultLeft, resultRight) {
                if (resultLeft.searchTextCount !== resultRight.searchTextCount) {
                  return resultRight.searchTextCount - resultLeft.searchTextCount;
                } else if (resultLeft.hitCount !== resultRight.hitCount) {
                  return resultRight.hitCount - resultLeft.hitCount;
                } else {
                  return resultRight.id - resultLeft.id;
                }
              });
              var searchResultList = '<ul class=\"search-result-list\">';
              resultItems.forEach(function (result) {
                searchResultList += result.item;
              })
              searchResultList += "</ul>";
              resultContent.innerHTML = searchResultList;
            }
          }

          if ('auto' === 'auto') {
            input.addEventListener('input', inputEventFunction);
          } else {
            $('.search-icon').click(inputEventFunction);
            input.addEventListener('keypress', function (event) {
              if (event.keyCode === 13) {
                inputEventFunction();
              }
            });
          }

          // remove loading animation
          $(".local-search-pop-overlay").remove();
          $('body').css('overflow', '');

          proceedsearch();
        }
      });
    }

    // handle and trigger popup window;
    $('.popup-trigger').click(function(e) {
      e.stopPropagation();
      if (isfetched === false) {
        searchFunc(path, 'local-search-input', 'local-search-result');
      } else {
        proceedsearch();
      };
    });

    $('.popup-btn-close').click(onPopupClose);
    $('.popup').click(function(e){
      e.stopPropagation();
    });
    $(document).on('keyup', function (event) {
      var shouldDismissSearchPopup = event.which === 27 &&
        $('.search-popup').is(':visible');
      if (shouldDismissSearchPopup) {
        onPopupClose();
      }
    });
  </script>





  

  

  

  
  

  

  

  


  
   <canvas class="fireworks" style="position: fixed;left: 0;top: 0;z-index: 1; pointer-events: none;"></canvas> 
   <script type="text/javascript" src="//cdn.bootcss.com/animejs/2.2.0/anime.min.js"></script> 
   <script type="text/javascript" src="/js/src/fireworks.js"></script>
  

</body>
</html>
